#!/bin/bash
#
# Copyright (C) 2017, 2025, Cyrus Li (e21920076@126.com). All rights reserved.
#

#
# The script will convert line endings from CRLF('\r\n') to LF('\n') and
# remove all spaces (' ' or '\t' mixed) at the end of lines.
# 1. To convert line endings from '\r\n' to '\n':
#    * bash: dos2unix
# 2. To remove all spaces at the end of lines:
#    * vim: %s/\s\+$//g
#    * sed: sed -i "s/[[:space:]]*$//g" <file>
#

NAME=$(basename $0)

cmd_dos2unix=/usr/bin/dos2unix

if [[ ! -x $cmd_dos2unix ]]; then
    echo "Oops, $cmd_dos2unix not found" >&2
    exit 1
fi

dir2backup=/tmp/.$NAME/$(date +"%m%d")
[[ ! -d $dir2backup ]] && mkdir -p $dir2backup

for file in $@; do
    [[ ! -f $file ]] && continue

    fbk=$dir2backup/$(basename $file).backup
    fr1=$dir2backup/$(basename $file).cat1
    fr2=$dir2backup/$(basename $file).cat2

    printf "Start to deal with file $file\n"
    printf "    1# backup $file to $fbk\n"
    cp $file $fbk
    printf "     # dos2unix $file\n"
    $cmd_dos2unix $file
    printf "    2# save $file via cat -A as $fr1\n"
    cat -A $file > $fr1
    printf "    3# remove spaces (' ' or '\t' mixed) at the end of lines\n"
    sed -i "s/[[:space:]]*$//g" $file
    printf "    4# save $file via cat -A again as $fr2\n"
    cat -A $file > $fr2

    printf "    5# diff $fr1 $fr2\n"
    if [[ -x ~/bin/colordiff ]]; then
        cmd_diff=~/bin/colordiff
    else
        cmd_diff=diff
    fi
    $cmd_diff -u $fr1 $fr2 | sed 's/^/       /g'
    printf "\n"
done

rm -f $f_dos2unix
exit 0
